package com.xxh.blog.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.xxh.blog.dao.UserDao;
import com.xxh.blog.entity.User;
import com.xxh.blog.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class auController {
    private static final String KAPSessionkey = "kap_key";

    @Autowired
    Producer producer;

    @Autowired
    UserDao userDao;

    @GetMapping("/captch.jpg")
    public void captch(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //生成验证码
        String code = producer.createText();
        //验证码存到session中
        request.getSession().setAttribute(KAPSessionkey, code);
        BufferedImage image = producer.createImage(code);
        response.setHeader("Cache-Control", "no-store");
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpeg", outputStream);
    }

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping("/login")
    public String login() {
        return "auth/login";
    }

    /**
     * 登录操作
     *
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result doLogin(String email, String password,HttpServletRequest request) {

        if (StrUtil.isEmpty(email) || StrUtil.isEmpty(password)) {
            return Result.error("用户名密码不能为空");
        }

        UsernamePasswordToken token = new UsernamePasswordToken(email, SecureUtil.md5(password));
        try {
            SecurityUtils.getSubject().login(token);
        } catch (UnknownAccountException uae) {
            //用户名未知...
            return Result.error("用户名未知");
        } catch (IncorrectCredentialsException ice) {
            //凭据不正确，例如密码不正确 ...
            return Result.error("密码不正确");
        } catch (LockedAccountException lae) {
            //用户被锁定，例如管理员把某个用户禁用...
            return Result.error("用户禁用");
        } catch (ExcessiveAttemptsException eae) {
            //尝试认证次数多余系统指定次数 ...
            return Result.error("登录次数过多，稍后再试");
        } catch (AuthenticationException ae) {
            //其他未指定异常
            return Result.error("我也不知道什么异常");
        }

        return Result.ok("登录成功").put("action", "/").put("status", 0);
    }

    /**
     * 注册操作
     *
     * @param user    注册填写的用户信息
     * @param vercode 发过来的验证码
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/reg")
    public Result doregist(User user, String vercode, HttpServletRequest request) {

        //从session中取出验证码
        String code = (String) request.getSession().getAttribute(KAPSessionkey);
        System.out.println(code);

        //验证验证码是否正确
        if (vercode == null || !vercode.equalsIgnoreCase(code)) {
            return Result.error("验证码错误");
        } else {
            //先判断用户是否存在
            Integer count = userDao.selectCount(new QueryWrapper<User>()
                    .eq("username", user.getUsername())
                    .or().eq("email", user.getEmail()));
            if (count == 0) {
                user.setPassword(SecureUtil.md5(user.getPassword()));
                userDao.insertSelective(user);
                return Result.ok().put("action", "/login").put("status", 0);
            } else {
                return Result.error("用户名已经,请更换");
            }

        }
    }


    /**
     * 跳转到注册页面
     *
     * @return
     */
    @GetMapping("/reg")
    public String register() {
        return "auth/reg";
    }

    /**
     * 登出
     * @return
     */
    @RequestMapping("/user/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }
}
